﻿using Common;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using Vision001.Views;

namespace Vision001
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        #region 异常处理函数

        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Mylog.Error(((e.ExceptionObject as Exception)).InnerException ?? throw new InvalidOperationException(), "未知的异常[CurrentDomain_UnhandledException]");
        }

        private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {
            e.SetObserved();
            Mylog.Error(e.Exception, "未知的异常[TaskScheduler_UnobservedTaskException]");
        }

        private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            Mylog.Error(e.Exception, "未知的异常[App_DispatcherUnhandledException]");
            e.Handled = true;
        }

        #endregion 异常处理函数

        private Mutex mutex;
        private string _msg = "证书错误！";
        private string sn = "";
        private HomeView homeView;

        //程序启动逻辑
        private void App_OnStartup(object sender, StartupEventArgs e)
        {
            bool res;
            mutex = new Mutex(true, "F001", out res);
            if (!res)
            {
                System.Windows.MessageBox.Show("程序已运行");
                //Environment.Exit(0);
                //Current.Shutdown();
                Process.GetCurrentProcess().Kill();
            }

            #region 异常处理

            DispatcherUnhandledException += App_DispatcherUnhandledException;

            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;

            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            //base.OnStartup(e);

            #endregion 异常处理

            try
            {
                //返回软件序列号，产品到期时间以及到期天数
                sn = License.GetSN(AppDomain.CurrentDomain.BaseDirectory + "license.sn");
                res = License.Check(out _msg);
            }
            catch (Exception ex)
            {
                res = false;
                Mylog.Error(ex);
            }

            if (res)
            {
                //验证通过,显示home界面
                var sn = License.GetSN(AppDomain.CurrentDomain.BaseDirectory + "license.sn");
                homeView = new HomeView(sn, _msg);
                homeView.Show();
            }
            else
            {
                //验证失败
                MessageBox.Show(_msg);
                Process.GetCurrentProcess().Kill();
            }
        }
    }
}